package com.easyattendance.services;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Student;
import com.easyattendance.model.StudentAttendance;
import com.easyattendance.model.StudentLeave;
import com.easyattendance.util.HibernateUtil;

public class AttendanceService {

	public ArrayList<Student> getStudentList(String classId) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		ArrayList<Student> studentList=new ArrayList<Student>();

		try {
			tx = session.beginTransaction();
			List<Student> studList = session.createQuery("FROM Student WHERE class_id='"+classId+"'").list();
			
			for(Iterator iterator =studList.iterator(); iterator.hasNext();)
			{
				 Student stud=(Student)iterator.next();
				 //String studid=stud.getStud_id();
				 int stud_rollno=stud.getStud_roll_no();
				 String stud_fnm=stud.getStud_fname();
				 String stud_lnm=stud.getStud_lname();
				 studentList.add(new Student(stud_rollno,stud_fnm,stud_lnm));
			}
			
			tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return studentList;
	}
	
	public ArrayList<StudentLeave> getStudentLeaveList(String classId) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		ArrayList<StudentLeave> studLeaveList=new ArrayList<StudentLeave>();
		

		try {
			tx = session.beginTransaction();
			List<StudentLeave> leaveList = session.createQuery("FROM StudentLeave WHERE class_id='"+classId+"' AND (leave_start_date<=CURDATE() AND leave_end_date>=CURDATE())").list(); 
				//Between CONVERT(leave_start_day,GETDATE()) AND CONVERT(leave_end_date),GETDATE())))").list();
			
			for(Iterator iterator =leaveList.iterator(); iterator.hasNext();)
			{
				 StudentLeave studleave=(StudentLeave)iterator.next();
				 int studid=studleave.getStud_roll_no();
				
				 studLeaveList.add(new StudentLeave(studid));
			}
			
			tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return studLeaveList;
	}
	
	public int[] getStudentPresentDays(String classId, java.sql.Timestamp startDate, java.sql.Timestamp endDate) {
		ArrayList<Student> studentList = getStudentList(classId);
		int[] studRollNos = new int[studentList.size()];
		int[] studPresentDays = new int[studentList.size()];
		int i=0;
		int presentCounter=0;
		Session session = HibernateUtil.openSession();
		Transaction tx = null;

		try {
			tx = session.beginTransaction();
			
			for(Iterator iterator = studentList.iterator(); iterator.hasNext(); ) {
				presentCounter=0;
				int studRollNo = ((Student)iterator.next()).getStud_roll_no();
				
				/*List<StudentAttendance> attendanceDatesList = session.createQuery("FROM StudentAttendance WHERE class_id='"+classId+"' "+
						"and stud_roll_no='"+studRollNo+"'").list();
				
				for(Iterator iterator2 =attendanceDatesList.iterator(); iterator2.hasNext();) {
					StudentAttendance stud=(StudentAttendance)iterator2.next();
					
					
				}*/
				
				List<StudentAttendance> studAttendanceList = session.createQuery("FROM StudentAttendance WHERE class_id='"+classId+"'"
						+ " and attendance_date<='"+endDate+"' and attendance_date>='"+startDate+"' and stud_roll_no='"+studRollNo+"'").list();
				
				for(Iterator iterator1 =studAttendanceList.iterator(); iterator1.hasNext();) {
					StudentAttendance stud=(StudentAttendance)iterator1.next();

					System.out.println("ATT DATE: "+stud.getAttendance_date());
					if(studRollNo == stud.getStud_roll_no()) {
						if(stud.getAttendance_status().equals("P")) {
							presentCounter++;
						}
					}
				}
				studPresentDays[i++] = presentCounter;
			}
			
			
			tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return studPresentDays;
	}
	
	public ArrayList<StudentAttendance> getAttendanceListByDate_ClassId(String classId, Date date) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		ArrayList<StudentAttendance> list = null;
		//String att_date=date+" 00:00:00";

		try {
			tx = session.beginTransaction();
			list = (ArrayList<StudentAttendance>) session.createQuery("FROM StudentAttendance WHERE class_id='"+classId+"' AND attendance_date='"+date+"'").list();

			tx.commit();

		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		if(list != null) {
			return list;
		}
		else {
			return null;
		}
		
	}

	/* UPDATE attednace status in db from editAttendance.jsp*/
	public boolean editAttendance(String studentRollNos[], Date date, String classId, String newStatus[]) {
		Session session = HibernateUtil.openSession();
		Transaction tx = null;
		StudentAttendance studAtt = null;
		
		try {
			tx = session.beginTransaction();
			//String att_date=date+" 00:00:00";
			for(int i=0; i<studentRollNos.length; i++) {
				Query query = session.createQuery("FROM StudentAttendance WHERE class_id='"+classId+"' AND attendance_date='"+date+"'"
						+ " AND stud_roll_no='"+studentRollNos[i]+"'");
				
				studAtt = (StudentAttendance) query.uniqueResult();
				
				if(studAtt != null) {
					if( ! studAtt.getAttendance_status().equals(newStatus[i])) {
						studAtt.setAttendance_status(newStatus[i]);
						
						/* update the new status to db */
						session.saveOrUpdate(studAtt);
					}
				}
				
			}
			tx.commit();
			if(studAtt != null)
				return true;
			else
				return false;
		} catch (HibernateException e) {
			if (tx != null) {
				tx.rollback();
				e.printStackTrace();
			}
			return false;
			
		} finally {
			session.close();
		}
	}
}

